package com.pai4j.ugc.service.chain;
import com.pai4j.common.enums.PromptTemplateEnum;
import com.pai4j.common.service.FreeMarkEngineService;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.domain.dto.aigc.ChatCompletionMessageRequest;
import com.pai4j.domain.dto.llm.ChatCompletionMessage;
import com.pai4j.domain.dto.llm.ChatCompletionResponse;
import com.pai4j.domain.vo.llm.ChatMessageRole;
import com.pai4j.domain.vo.response.moment.AiContent;
import com.pai4j.domain.vo.response.moment.MomentVO;
import com.pai4j.ugc.service.MoonshotAIService;
import com.pai4j.ugc.repository.dao.IMomentAiContentDAO;
import com.pai4j.ugc.repository.dao.IMomentAiKeywordDAO;
import com.pai4j.ugc.service.ai.AiContentPersistService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.pai4j.ugc.service.ai.AiContentRetryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class MomentReviewHandler implements MomentPublishHandler {


    @Autowired
    private FreeMarkEngineService freeMarkEngineService;

    @Autowired
    private AiContentRetryService aiContentRetryService;

    @Autowired
    private AiContentPersistService aiContentPersistService;

    @Resource
    private MoonshotAIService moonshotAIService;

    @Override
    public void handle(MomentVO moment, MomentPublishHandlerChain chain) throws Exception {

        // 这里我们仅支持对正文内容的审核
        String content = moment.getContent();
        if (StringUtils.isBlank(content)) {
            chain.handle(moment, chain);
            return;
        }

        String templateName = PromptTemplateEnum.MOMENT_REVIEW.getPath();
        Map<String, Object> vars = new HashMap<>();
        vars.put("author", "程序员pai");
        vars.put("input", content);
        String prompt;
        try {
            prompt = freeMarkEngineService.getContentByTemplate(templateName, vars);
        } catch (Exception e) {
            log.error("[朋友圈内容审核异常] ===> prompt模版引擎模版渲染失败！vars:{}",
                    JsonUtil.toJsonString(vars), e);
            chain.handle(moment, chain);
            return;
        }
        // 将用户的提示信息封装成一个ChatCompletionMessage对象，并创建一个包含该消息的列表
        // 这里只包含一个消息，因为当前场景是一次用户请求对应一次模型回复
        ChatCompletionMessageRequest chatCompletionMessageRequest = new ChatCompletionMessageRequest(prompt,null,null);
        final List<ChatCompletionMessage> messageList = Arrays.asList(
                new ChatCompletionMessage(ChatMessageRole.USER.value(),
                        chatCompletionMessageRequest.getPrompt()));

        ChatCompletionResponse chatCompletionResponse = moonshotAIService.chat(messageList);
        Integer reviewScore = null;
        AiContent aiContent  = new AiContent();
        if (chatCompletionResponse != null ) {
            String contentStr = chatCompletionResponse.getChoices().get(0).getMessage().getContent();
            aiContent = JsonUtil.fromJson(contentStr, AiContent.class);
            if (aiContent != null) {
                reviewScore = StringUtils.isNoneBlank(String.valueOf(aiContent.getQualityScore())) ? aiContent.getQualityScore() : null;
            } else {
                // AI响应解析失败，设置默认审核分数
                log.warn("[π圈内容审核] AI响应解析失败，设置默认审核分数: momentId={}, originalResponse={}", moment.getId(), contentStr);
                // 设置默认分数，触发人工审核
                reviewScore = 5;

            }
            log.info("[π圈内容审核结果] ===> 内容:{}", aiContent);
        // 持久化AI分析结果 + 关键词索引（事务）
        try {
            aiContentPersistService.persistAiAnalysis(moment.getId(), aiContent);
        } catch (Exception e) {
            log.error("[π圈AI内容/关键词持久化失败] momentId={}, aiContent={}", moment.getId(), JsonUtil.toJsonString(aiContent), e);
            aiContentRetryService.recordPersistFail(moment.getId(), aiContent, e.getMessage());
        }

        } else {
            log.error("[π内容审核异常] ===> LLM Chat Error！prompt:{}", prompt);
            chain.handle(moment, chain);
            return;
        }

        moment.setAiContent(aiContent);
        moment.setReviewScore(reviewScore);
        chain.handle(moment, chain);
    }
}